package com.pro.controller;

import com.pro.pojo.JsUser;
import com.pro.pojo.JsonData;
import com.pro.service.LoginService;
import com.pro.utils.RedisCache;
import com.pro.utils.VerificationCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
* @author ：刘弘禹
* @description：TODO
* @date ：2022/1/7 15:31
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
   private RedisCache redisCache;

    @Autowired
    private HttpSession httpSession;

    // 原请求信息的缓存及恢复
    private RequestCache requestCache = new HttpSessionRequestCache();
    // 用于重定向
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @RequestMapping("/login")
    public void getUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest request1 = requestCache.getRequest(request, response);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        UserDetails userDetails = userDetailsService.loadUserByUsername(name);
        JsUser login = loginService.login(name, userDetails.getPassword());
        if(login != null){
            redirectStrategy.sendRedirect(request, response, "/index.html");
       }else{
            redirectStrategy.sendRedirect(request, response, "/login/login.html");
        }
    }

    //向页面添加验证码图片
    @RequestMapping("/getVerify")
   public void getVerify(HttpServletResponse response,HttpServletRequest request){
       try {
            response.setContentType("image/jpeg");
            response.setHeader("Pragma", "No-cache");
           response.setHeader("Cache-Control", "no-cache");
           response.setDateHeader("Expire", 0);
          VerificationCodeUtils randomValidateCode = new VerificationCodeUtils();
           randomValidateCode.getRandcode(request, response);
        } catch (Exception e) {
           e.printStackTrace();
       }
   }

   //验证码验证
    @RequestMapping(value = "/getVerification",method = RequestMethod.POST)
   @ResponseBody
    public JsonData verification(String verificationCode){
        String random ;
        random = (String) httpSession.getAttribute("RANDOMVALIDATECODEKEY");
        if (random.equals(verificationCode.toUpperCase())) {
           return random != null ? JsonData.buildSuccess(true) : JsonData.buildError("服务端错误");
       }
        return random != null ? JsonData.buildSuccess(false) : JsonData.buildError("服务端错误");
    }


   @RequestMapping("/getUser")
    @ResponseBody
   public JsonData getUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       String name = authentication.getName();
      Object cacheObject = redisCache.getCacheObject("user:" + name);
      return cacheObject != null ? JsonData.buildSuccess(cacheObject) : JsonData.buildError("服务端错误");
   }

   /* 功能描述: <br>
   * 〈登出〉
   *
   * @param
   * @return: java.lang.String
   * @Author: Kai
   * @Date: 2022/2/22 上午 09:03
   */
    @RequestMapping("/loginOut")
    @ResponseBody
    public String logOut(HttpSession session){
        session.removeAttribute("user");
        session.invalidate();
        return "true";
    }
}
